package com.ipan.jfinal.template;

import javax.servlet.http.HttpServletRequest;

import com.ipan.jfinal.plugin.userinfo.UserInfoManager;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

/**
 * 不存在角色验证指令
 * 
 * @author iPan
 * @version 2018-05-15
 */
public class NoRoleDirective extends Directive {
	
	private String[] roles = null;
	private Object mark = null; // 多端会话区分
	

	protected boolean hasRole(Scope scope) {
		HttpServletRequest request = (HttpServletRequest) scope.getRootData().get("request");
		String markStr = null;
		if (mark instanceof com.jfinal.template.expr.ast.Field) {
			markStr = (String) ((com.jfinal.template.expr.ast.Field)mark).eval(scope);
		} else {
			markStr = mark.toString();
		}
		return !UserInfoManager.hasRole(request, markStr, roles);
	}
	
	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		if (hasRole(scope)) {
			stat.exec(env, scope, writer);
		}
	}
	
	@Override
	public void setExprList(ExprList exprList) {
		this.exprList = exprList;
		int paraNum = exprList.length();
		if (paraNum < 2) {
			throw new ParseException("#noRole 参数异常", location);
		}
		Expr[] arr = exprList.getExprArray();
		this.roles = new String[arr.length - 1];
		for (int i=1; i<arr.length; ++i) {
			this.roles[i - 1] = arr[i].toString();
		}
		this.mark = arr[0];
	}

	@Override
	public boolean hasEnd() {
		return true;
	}
	
}
